﻿using OL.FrameCore.Application.Dept.Dto;
using OL.FrameCore.Domain.Entity;
using OL.FrameCore.Infrastructure.UnitOfWork;
//using OL.FrameCore.Domain.IRepository;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using OL.FrameCore.Repository.EF;

namespace OL.FrameCore.Application.Dept
{
    public class DeptService :  IDeptService
    {
        //IDeptRepository _repository;
        IUnitOfWork _unitOfwork;
        //IUnitOfWork<ReadOnlyDataContext> _unitOfwork;
        public DeptService(IUnitOfWork unitOfwork)
        {
            _unitOfwork = unitOfwork;
        }

        /// <summary>
        /// 获取所有部门列表
        /// </summary>
        /// <returns></returns>
        public IList<GetDeptListModel> GetAllDeptList()
        {
            var repositoryDept = _unitOfwork.GetRepository<SysDept>();
            var query = from a in repositoryDept.TableNoTracking
                        where a.IsDelete== false
                        orderby a.SortIndex
                        select new GetDeptListModel
                        {
                            Id = a.Id,
                            DeptName = a.DeptName,
                            ParentId = a.ParentId,
                            DeptLevel = a.DeptLevel,
                            SortIndex = a.SortIndex
                        };
            return query.ToList();
        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public PageData<GetDeptListModel> GetDeptList(GetDeptListRequest request)
        {
            var repositoryDept = _unitOfwork.GetRepository<SysDept>();
            var query = from a in repositoryDept.TableNoTracking
                        join b in repositoryDept.TableNoTracking on a.ParentId equals b.Id into tmpB
                        from b in tmpB.DefaultIfEmpty()
                        where a.IsDelete == false
                        && (request.DeptId.HasValue ? a.Id == request.DeptId : true)
                        && (string.IsNullOrEmpty(request.DeptName) ? true : a.DeptName == request.DeptName)
                        && (string.IsNullOrEmpty(request.DeptCode) ? true : a.DeptCode == request.DeptCode)
                        && (request.ParentId.HasValue ? a.ParentId == request.ParentId : true)
                        orderby a.UpdateTime descending
                        select new GetDeptListModel
                        {
                            Id = a.Id,
                            DeptName = a.DeptName,
                            DeptCode = a.DeptCode,
                            ParentId = a.ParentId,
                            ParentName = b.DeptName?? "根部门",
                            DeptLevel = a.DeptLevel,
                            SortIndex = a.SortIndex,
                            CreateTime = a.CreateTime
                        };
            return repositoryDept.PagingAsync<GetDeptListModel>(query, request.PageIndex, request.PageSize).Result;
        }
        /// <summary>
        /// 获取部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public GetDeptResponse GetDept(int id)
        {
            var repositoryDept = _unitOfwork.GetRepository<SysDept>();
            var model = repositoryDept.TableNoTracking.Where(p => p.Id == id && p.IsDelete == false).SingleOrDefault();
            if (model == null)
                throw new Exception($"未找到部门 id:{id}");

            return new GetDeptResponse
            {
                Id = model.Id,
                DeptName = model.DeptName,
                DeptCode = model.DeptCode,
                ParentId = model.ParentId,
                //DeptLevel = model.DeptLevel,
                SortIndex = model.SortIndex,
                Remark = model.Remark
            };
        }
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Result AddDept(AddDeptRequest request)
        {
            var repositoryDept = _unitOfwork.GetRepository<SysDept>();

            if (repositoryDept.TableNoTracking.Any(p => p.DeptCode == request.DeptCode && p.IsDelete == false))
            {
                return new FailResult("部门编号已存在");
            }

            repositoryDept.Insert(new SysDept
            {
                DeptName = request.DeptName,
                DeptCode = request.DeptCode,
                ParentId = request.ParentId,
                SortIndex = request.SortIndex,
                DeptLevel = request.DeptLevel,
                Remark = request.Remark ?? "",
                CreateId = request.OpeatorId,
                CreateTime = DateTime.Now,
                UpdateId = request.OpeatorId,
                UpdateTime = DateTime.Now,
                IsDelete = false
            });

            return new SuccessResult();
        }
        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Result UpdateDept(UpdateDeptRequest request)
        {
            var repositoryDept = _unitOfwork.GetRepository<SysDept>();
            var model = repositoryDept.TableNoTracking.Where(p => p.Id == request.Id && p.IsDelete == false).SingleOrDefault();
            if (model == null)
            {
                return new FailResult("找不到数据，请刷新后重试");
            }

            model.DeptName = request.DeptName;
            model.DeptCode = request.DeptCode;
            model.SortIndex = request.SortIndex;
            model.ParentId = request.ParentId;
            model.Remark = request.Remark ?? "";
            model.UpdateId = request.OpeatorId;
            model.UpdateTime = DateTime.Now;
            repositoryDept.Update(model);

            return new SuccessResult();
        }
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Result DeleteDept(int id, int opeatorId)
        {
            var repositoryDept = _unitOfwork.GetRepository<SysDept>();
            var model = repositoryDept.Table.Where(p => p.Id == id && p.IsDelete == false).SingleOrDefault();
            if (model == null)
            {
                return new FailResult("找不到数据，请刷新后重试");
            }

            var repositorySysUser = _unitOfwork.GetRepository<SysUser>();
            if (repositorySysUser.TableNoTracking.Any(p => p.DeptId == id && p.IsDelete == false))
            {
                return new FailResult("部门数据已被引用，不允许直接删除");
            }

            model.IsDelete = true;
            model.UpdateId = opeatorId;
            model.UpdateTime = DateTime.Now;
            _unitOfwork.Save();

            return new SuccessResult();
        }
    }
}
